<template>
  <div class="user-list">
    <el-card class="list-card">
      <template #header>
        <div class="card-header">
          <span class="title">用户管理</span>
        </div>
      </template>

      <div class="content-wrapper">
        <!-- 搜索栏 -->
        <div class="filter-container">
          <div class="filter-left">
            <el-input
              v-model="searchForm.username"
              placeholder="请输入用户名"
              class="filter-item"
              style="width: 200px"
              clearable
              @keyup.enter="handleSearch"
            />
            <el-select 
              v-model="searchForm.role" 
              placeholder="请选择角色" 
              class="filter-item" 
              style="width: 240px"
              clearable
            >
              <el-option label="超级管理员" value="superadmin" />
              <el-option label="管理员" value="admin" />
              <el-option label="学生" value="student" />
            </el-select>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
            <el-button @click="resetSearch">重置</el-button>
          </div>
        </div>

        <!-- 新增用户按钮 -->
        <el-button type="primary" class="add-button" @click="handleAdd">
          <el-icon><Plus /></el-icon>新增用户
        </el-button>

        <!-- 表格部分 -->
        <div class="table-container">
          <el-table v-loading="loading" :data="userList" border>
            <el-table-column prop="username" label="用户名" />
            <el-table-column prop="realName" label="真实姓名" />
            <el-table-column label="角色" align="center">
              <template #default="{ row }">
                <el-tag 
                  :type="getRoleType(row.role)"
                  :class="`role-${row.role}`"
                  size="small"
                  effect="plain"
                >
                  {{ getRoleLabel(row.role) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="phone" label="手机号码" />
            <el-table-column prop="email" label="邮箱" />
            <el-table-column label="操作" width="280">
              <template #default="{ row }">
                <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
                <el-button type="warning" link @click="handleResetPassword(row)">重置密码</el-button>
                <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination">
            <el-pagination
              v-model:current-page="currentPage"
              v-model:page-size="pageSize"
              :total="userList.length"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, sizes, prev, pager, next"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
      </div>
    </el-card>

    <!-- 用户表单对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
      @close="resetForm"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        :rules="userRules"
        label-width="100px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="userForm.password" type="password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="realName">
          <el-input v-model="userForm.realName" placeholder="请输入真实姓名" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" placeholder="请选择角色">
            <el-option 
              v-for="option in getRoleOptions" 
              :key="option.value" 
              :label="option.label" 
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号码" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>

    <!-- 重置密码对话框 -->
    <el-dialog
      title="重置用户密码"
      v-model="resetPasswordDialogVisible"
      width="400px"
    >
      <el-form
        ref="resetPasswordFormRef"
        :model="resetPasswordForm"
        :rules="resetPasswordRules"
        label-width="100px"
      >
        <el-form-item label="新密码" prop="password">
          <el-input
            v-model="resetPasswordForm.password"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="resetPasswordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetPasswordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitResetPassword">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance } from 'element-plus'
import * as userApi from '@/api/user'
import { useStore } from 'vuex'

const store = useStore()

// 搜索表单
const searchForm = reactive({
  username: '',
  role: ''
})

// 用户表单
const userForm = reactive({
  id: undefined,
  username: '',
  password: '',
  realName: '',
  role: '',
  phone: '',
  email: ''
})

// 用户表单验证规则
const userRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, message: '用户名长度不能小于3位', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' }
  ],
  role: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '请输入手机号码', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 列表数据
const loading = ref(false)
const userList = ref<any[]>([])
const currentPage = ref(1)
const pageSize = ref(10)

// 获取用户列表
const fetchUserList = async () => {
  try {
    loading.value = true;
    const res = await userApi.getUserList({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      username: searchForm.username,
      role: searchForm.role
    });
    
    const data = (res as any).data;
    userList.value = data.records || [];
    currentPage.value = data.current || 1;
    pageSize.value = data.size || 10;

  } catch (error) {
    console.error('获取用户列表失败:', error);
    ElMessage.error('获取用户列表失败');
  } finally {
    loading.value = false;
  }
};

// 角色标签类型
const getRoleType = (role: string) => {
  const cleanRole = role.replace(/[\[\]]/g, '')
  switch (cleanRole) {
    case 'superadmin':
      return 'danger'
    case 'admin':
      return 'warning'
    case 'counselor':
      return 'success'
    case 'student':
      return 'info'
    default:
      return ''
  }
}

// 角色标签文本
const getRoleLabel = (role: string) => {
  const cleanRole = role.replace(/[\[\]]/g, '')
  switch (cleanRole) {
    case 'superadmin':
      return '超级管理员'
    case 'admin':
      return '管理员'
    case 'counselor':
      return '咨询师'
    case 'student':
      return '学生'
    default:
      return cleanRole
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchUserList()
}

const resetSearch = () => {
  searchForm.username = ''
  searchForm.role = ''
  handleSearch()
}

// 分页
const handleSizeChange = (val: number) => {
  pageSize.value = val
  fetchUserList()
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
  fetchUserList()
}

// 表单操作
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const dialogTitle = computed(() => dialogType.value === 'add' ? '新增用户' : '编辑用户')
const userFormRef = ref<FormInstance>()

const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row: any) => {
  dialogType.value = 'edit'
  resetForm()
  Object.assign(userForm, {
    id: row.id,
    username: row.username,
    realName: row.realName,
    role: row.role.replace(/[\[\]]/g, ''),
    phone: row.phone,
    email: row.email
  })
  dialogVisible.value = true
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该用户吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await userApi.deleteUser(row.id)
      ElMessage.success('删除成功')
      fetchUserList()
    } catch (error) {
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  })
}

const submitForm = async () => {
  if (!userFormRef.value) return
  
  await userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await userApi.addUser(userForm)
          ElMessage.success('添加成功')
        } else {
          await userApi.updateUser(userForm.id!, userForm)
          ElMessage.success('修改成功')
        }
        dialogVisible.value = false
        fetchUserList()
      } catch (error) {
        console.error('保存用户失败:', error)
        ElMessage.error('保存用户失败')
      }
    }
  })
}

const resetForm = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields()
  }
  Object.assign(userForm, {
    id: undefined,
    username: '',
    password: '',
    realName: '',
    role: '',
    phone: '',
    email: ''
  })
}

// 初始化
onMounted(() => {
  fetchUserList()
})

// 在角色选项中添加权限控制
const getRoleOptions = computed(() => {
  const currentRole = store.state.user.role
  
  if (currentRole === 'superadmin') {
    return [
      { label: '超级管理员', value: 'superadmin' },
      { label: '管理员', value: 'admin' },
      { label: '学生', value: 'student' }
    ]
  } else if (currentRole === 'admin') {
    return [
      { label: '学生', value: 'student' }
    ]
  } else {
    return [] // 其他角色不显示角色选项
  }
})

// 重置密码相关
const resetPasswordDialogVisible = ref(false)
const resetPasswordFormRef = ref<FormInstance>()
const resetPasswordForm = reactive({
  userId: 0,
  password: '',
  confirmPassword: ''
})

// 重置密码表单验证规则
const resetPasswordRules = {
  password: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (value !== resetPasswordForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 处理重置密码
const handleResetPassword = (row: any) => {
  resetPasswordForm.userId = row.id
  resetPasswordForm.password = ''
  resetPasswordForm.confirmPassword = ''
  resetPasswordDialogVisible.value = true
}

// 提交重置密码
const submitResetPassword = async () => {
  if (!resetPasswordFormRef.value) return
  
  try {
    await resetPasswordFormRef.value.validate()
    await userApi.resetUserPassword(resetPasswordForm.userId, resetPasswordForm.password)
    ElMessage.success('密码重置成功')
    resetPasswordDialogVisible.value = false
  } catch (error: any) {
    ElMessage.error('密码重置失败：' + (error.message || '未知错误'))
  }
}
</script>

<style lang="scss" scoped>
.user-list {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  .list-card {
    .card-header {
      .title {
        font-size: 18px;
        font-weight: bold;
        color: #303133;
      }
    }

    .content-wrapper {
      background-color: #fff;
      padding: 15px;
    }

    .filter-container {
      margin-bottom: 15px;

      .filter-left {
        display: flex;
        align-items: center;
        gap: 10px;
      }

      .filter-item {
        margin: 0;
      }
    }

    .add-button {
      margin-bottom: 15px;
    }

    .table-container {
      .el-table {
        width: 100%;
      }
    }

    /* 分页样式 */
    .pagination {
      margin-top: 15px;
      display: flex;
      justify-content: flex-end;
    }
  }

  :deep(.el-tag) {
    padding: 0 8px;
    height: 22px;
    line-height: 20px;
    border-radius: 2px;
    font-size: 12px;
    border-width: 1px;
    
    &.role-superadmin {
      color: #F56C6C;
      background: rgba(245, 108, 108, 0.15);
      border-color: #F56C6C;
    }
    
    &.role-admin {
      color: #E6A23C;
      background: rgba(230, 162, 60, 0.15);
      border-color: #E6A23C;
    }
    
    &.role-counselor {
      color: #67C23A;
      background: rgba(103, 194, 58, 0.15);
      border-color: #67C23A;
    }
    
    &.role-student {
      color: #909399;
      background: rgba(144, 147, 153, 0.15);
      border-color: #909399;
    }
  }
}
</style> 